package databases

import (
	"errors"
	"github.com/go-xorm/xorm"
	"gitlab.gaodun.com/golib/gderror"
	"permission/config"
	"permission/vigo_loger"
)

type FunctionsFactory struct {
	Table        Tpo_Sys_Functions
	engine       *xorm.Engine
	RowsSlicePtr []Tpo_Sys_Functions
	UserFuncPtr  []UserNavFunc
}

// 返回 user factory
func NewFuncFactory() *FunctionsFactory {
	funcFac := FunctionsFactory{}
	funcFac.engine, _ = config.InitEng()
	return &funcFac
}

func (fcf *FunctionsFactory) FindInfoByAppId(appId int32) error {
	if appId == 0 {
		return errors.New("appId is null")
	}
	err := fcf.engine.Where(" AppId = ? ", appId).Find(&(fcf.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}

	return err
}

func (fcf *FunctionsFactory) FindInfoByUserAndAppId(appId int32, userId int64) error {
	return fcf.engine.Join("INNER", "Tpo_Sys_User_Navigation_Function", "Tpo_Sys_User_Navigation_Function.FunctionId=Tpo_Sys_Functions.FunctionId").Where("Tpo_Sys_User_Navigation_Function.UserId = ? and Tpo_Sys_Functions.AppId = ?", userId, appId).Find(&(fcf.UserFuncPtr))
}

func (uff *FunctionsFactory) FindInfoByFuncKey(appId int32, funcKey string) error {
	uff.RowsSlicePtr = []Tpo_Sys_Functions{}
	err := uff.engine.Where("AppId = ? and FunctionKey = ?", appId, funcKey).Find(&(uff.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}

	return err
}

// 根据角色获取菜单功能
func (fcf *FunctionsFactory) FindFunctionByRoleIds(roleIds ...int64) error {
	if len(roleIds) == 0 {
		return errors.New("role id is null")
	}
	// err := rnf.engine.Join("INNER", "Tpo_Sys_Functions", "Tpo_Sys_Role_Navigation_Function.FunctionId=Tpo_Sys_Functions.FunctionId").In("RoleId", roleIds).Find(&(rnf.RowsSlicePtrFunc))
	err := fcf.engine.Join("INNER", "Tpo_Sys_Role_Navigation_Function", "Tpo_Sys_Role_Navigation_Function.FunctionId=Tpo_Sys_Functions.FunctionId").In("RoleId", roleIds).Find(&(fcf.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}
	return err
}